package bioinfo;

import bioinfo.stats.*;

import java.io.*;
import au.com.bytecode.opencsv.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Properties;
import javax.swing.table.TableModel;
import javax.swing.table.AbstractTableModel;

public class Main extends JFrame {

    public static Vector<String> categs;
    public static Vector<String> sousCategs;
    public static Vector<String> noms;
    public static Vector<ARN> arns;

    public static String file;

    Stats st;
    JPanel jp_glob;
    JPanel jp_stats;
    JPanel jp_search;
    JPanel jp_results;
    JPanel jp_infos;

    JScrollPane jsp_results;

    JLabel jl_infos;
    JTable jt_arns;

    JTextField jtf_search;

    JMenuBar menuBar;

    public Main() {
        super("BioInformatique");

        jp_glob = new JPanel(new BorderLayout());
        jp_search = new JPanel(new BorderLayout());

        /* GENERALITES */
        jl_infos = new JLabel(arns.size() + " ARNt, répartis en " + categs.size() + " catégories (" + sousCategs.size() + " sous-catégories)");

        TableModel dataModel = new AbstractTableModel() {
            public int getColumnCount() { return 7; }
            public int getRowCount() { return arns.size();}
            public String getColumnName(int col) {
                String res;

                switch(col) {
                    case 0:
                        res = "Category";
                        break;
                    case 1:
                        res = "Subcategory";
                        break;
                    case 2:
                        res = "Name";
                        break;
                    case 3:
                        res = "Name details";
                        break;
                    case 4:
                        res = "Sequence";
                        break;
                    case 5:
                        res = "Anticodon";
                        break;
                    case 6:
                        res = "Str";
                        break;
                    default:
                        res = "Name";
                        break;
                }

                return res;
            }
            public Object getValueAt(int row, int col) {
                ARN arn_tmp = arns.get(row);

                Object res;

                switch(col) {
                    case 0:
                        res = arn_tmp.getCateg();
                        break;
                    case 1:
                        res = arn_tmp.getSousCateg();
                        break;
                    case 2:
                        res = arn_tmp.getNom();
                        break;
                    case 3:
                        res = arn_tmp.getNomDetail();
                        break;
                    case 4:
                        res = arn_tmp.getSeq();
                        break;
                    case 5:
                        res = arn_tmp.getAnticodon();
                        break;
                    case 6:
                        res = arn_tmp.getStr();
                        break;
                    default:
                        res = arn_tmp.getNom();
                        break;
                }

                return res;
            }
        };
        jt_arns = new JTable(dataModel);
        JScrollPane scrollpane = new JScrollPane(jt_arns);

        jp_glob.add(jl_infos, BorderLayout.NORTH);
        jp_glob.add(scrollpane);

        add(jp_glob);
        createMenuBar();

        pack();
    }

    private void createMenuBar() {
        menuBar = new JMenuBar();

        JMenu file = new JMenu("File");

        JMenuItem general = new JMenuItem("General");
        general.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Main.this.remove(jp_glob);
                if(st != null)
                    Main.this.remove(st.getPanel());

                Main.this.add(jp_glob);
                Main.this.validate();
            }
        });

        JMenuItem quit = new JMenuItem("Quit");
        quit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));

        file.add(general);
        file.add(quit);

        JMenu stats = new JMenu("Stats");
        JMenuItem first = new JMenuItem("Statistiques générales");
        first.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Main.this.remove(jp_glob);
                if(st != null)
                    Main.this.remove(st.getPanel());

                st = new First();
                Main.this.add(st.getPanel());
                Main.this.validate();
            }
        });

        stats.add(first);

        JMenuItem second = new JMenuItem("Pourcentage d'apparition des anticodons");
        second.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Main.this.remove(jp_glob);
                if(st != null)
                    Main.this.remove(st.getPanel());

                st = new Second();
                Main.this.add(st.getPanel());
                Main.this.validate();
            }
        });

        stats.add(second);

        JMenuItem third = new JMenuItem("Apparition d'un anticodon / longueur de la séquence");
        third.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Main.this.remove(jp_glob);
                if(st != null)
                    Main.this.remove(st.getPanel());

                st = new Third();
                Main.this.add(st.getPanel());
                Main.this.validate();
            }
        });

        stats.add(third);

        menuBar.add(file);
        menuBar.add(stats);

        setJMenuBar(menuBar);
    }

    // Initialisation du vecteur contenant les ARN et des vecteurs de catégories/sous-catégories
    public static void init() {
        arns = new Vector<ARN>();
        categs = new Vector<String>();
        sousCategs = new Vector<String>();
        noms = new Vector<String>();

        try {
            CSVReader reader = new CSVReader(new FileReader(file));        
            String[] nextLine;

            while ((nextLine = reader.readNext()) != null) {
                ARN a = new ARN(nextLine[0], nextLine[1], nextLine[2], nextLine[3], Integer.parseInt(nextLine[4]),
                        nextLine[5], nextLine[6], Integer.parseInt(nextLine[7]), nextLine[8], nextLine[9]);
                arns.add(a);

                // On mémorise la catégorie et la sous-catégorie
                if (!Main.contains(categs, a.getCateg()))
                    categs.add(a.getCateg());

                if (!Main.contains(sousCategs, a.getSousCateg()))
                    sousCategs.add(a.getSousCateg());

                if (!Main.contains(noms, a.getNom()))
                    noms.add(a.getNom());

            }

        } catch (Exception e) { 
            System.out.println("Error >> File "+file+" not found."); 
        }
    }

    public static boolean contains(Vector<String> v, String s) {
        int n = v.size();
        for (int i = 0; i < n; i++) {
            if (v.get(i).compareTo(s) == 0)
                return true;
        }

        return false;
    }

    public static void main(String[] args) {
        if (args.length < 1 || args.length > 1) {
            File tmp = new File("database.csv");
            if(!tmp.exists()) {
                System.err.println("Erreur >> Usage : java -jar bioinfo-cd.jar <file>.");
                System.exit(0);
            }
            file = "database.csv";
        }
        else {
            file = args[0];
        }

        init();
        Main m = new Main();
        m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //m.setExtendedState(JFrame.MAXIMIZED_BOTH);
        m.setVisible(true);
    }
}
